<script setup lang="ts">
import { addPublish, deletePublish, editPublish, getPublish } from "@/api/book";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, getCurrentInstance } from "vue";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "Publish"
});

onMounted(() => {
  onSearch();
});

const { proxy } = getCurrentInstance();
const loading = ref(true);
const tableData = ref([]);

const pagerConfig = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
  keyword: ""
});

const columns = reactive([
  {
    prop: "name",
    label: "出版社"
  },
  {
    prop: "email",
    label: "邮箱"
  }
]);

async function onSearch() {
  loading.value = true;
  let result = await getPublish(pagerConfig);
  pagerConfig.total = result.total;
  tableData.value = result.data;
}

const handleSearch = () => {
  pagerConfig.pageSize = 10;
  onSearch();
};

const handlePageChange = page => {
  pagerConfig.currentPage = page;
  onSearch();
};

// 添加的 form 数据
const form = reactive({
  id: "",
  name: "",
  email: ""
});

const formRef = ref();

const formLabelWidth = "80px";

// 控制模拟态框的显示隐藏
const dialogVisible = ref(false);
// 区分编辑和新增
const action = ref("add");
const addClick = () => {
  dialogVisible.value = true;
  loading.value = false;
  action.value = "add";
};

const editClick = row => {
  dialogVisible.value = true;
  loading.value = false;
  action.value = "edit";
  form.id = row.id;
};

const deleteClick = row => {
  ElMessageBox.confirm("确定要删除吗?")
    .then(async () => {
      await deletePublish(row.id);
      ElMessage({
        showClose: true,
        message: "删除出版社成功",
        type: "success"
      });
      onSearch();
    })
    .catch(() => {
      // catch error
    });
};

async function onSubmit() {
  (proxy.$refs.formRef as any).validate(async valid => {
    if (valid) {
      if (action.value == "add") {
        console.log(form);
        await addPublish(form);
        ElMessage.success("新增出版社成功~");
        onSearch();
        dialogVisible.value = false;
      } else if (action.value == "edit") {
        await editPublish(form);
        ElMessage.success("修改出版社成功~");
        onSearch();
        dialogVisible.value = false;
      }
      formRef.value.resetFields();
    } else {
      ElMessage({
        showClose: true,
        message: "表单格式错误！",
        type: "error"
      });
    }
  });
}

const cancelForm = () => {
  dialogVisible.value = false;
  formRef.value.resetFields();
};

const onClick = () => {
  onSubmit();
};

const rules = reactive<any>({
  name: [{ required: true, message: "必选项" }],
  email: [
    { required: true, message: "必选项" },
    { type: "email", message: "邮箱格式错误" }
  ]
});
</script>

<template>
  <div class="book">
    <div class="header">
      <el-button type="primary" @click="addClick">+新增</el-button>
      <el-form :inline="true">
        <el-form-item label="请输入">
          <el-input
            v-model="pagerConfig.keyword"
            placeholder="请输入出版社名"
            style="width: 400px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table">
      <el-table :data="tableData">
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
        >
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editClick(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="deleteClick(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        small
        background
        layout="total, prev, pager, next"
        :total="pagerConfig.total"
        class="pager mt-4"
        @current-change="handlePageChange"
      />
    </div>

    <el-drawer
      v-model="dialogVisible"
      :title="action === 'add' ? '新增出版社' : '编辑出版社'"
      class="demo-drawer"
      :close="cancelForm"
    >
      <div class="demo-drawer__content">
        <el-form :model="form" ref="formRef" :rules="rules">
          <el-form-item
            label="出版社名"
            prop="name"
            :label-width="formLabelWidth"
          >
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
            <el-input v-model.number="form.email" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取消</el-button>
          <el-button type="primary" :loading="loading" @click="onClick">
            {{ loading ? "提交中 ..." : "提交" }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped>
.book {
  display: flex;
  justify-content: center;
  flex-direction: column;
  padding: 50px;
}

.header {
  display: flex;
  justify-content: space-between;
}

.table {
  margin-top: 20px;
  height: 620px;
}

.pager {
  display: flex;
  justify-content: flex-end;
}
</style>
